package cn.tedu.ssm.Controller;

import cn.tedu.ssm.pojo.Good;
import cn.tedu.ssm.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("goods")
public class GoodController {
    @Autowired
    private GoodService goodService;
    @ResponseBody
    @GetMapping("list")
    public Map<String, Object> list(@RequestParam(name = "page", required = false) Integer page, @RequestParam(name = "size",required = false) Integer size){
        return goodService.list(page, size);
    }

    @ResponseBody
    @RequestMapping("update")
    public Long update(Long id, String name, Float price){
        return goodService.update(id, name, price);
    }

    @ResponseBody
    @RequestMapping("edit")
    public Long edit(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (id != null && id > 0){
            request.getSession().setAttribute("goodid",id);
        }
        response.sendRedirect("/?target=goods-edit");
        return id;
    }

    @ResponseBody
    @RequestMapping("getGoodId")
    public Map getGoodId(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session.getAttribute("goodid") == null){
            return null;
        }
        Good good = goodService.findById((Long) session.getAttribute("goodid"));
        Map<String, Object> map = new HashMap<>();
        map.put("id",good.getId());
        map.put("name",good.getName());
        map.put("price",good.getPrice());
        return map;
    }
    @ResponseBody
    @RequestMapping("remove")
    public int removeAttr(HttpServletRequest request){
        request.getSession().removeAttribute("goodid");
        return 1;
    }
    @ResponseBody
    @RequestMapping("save")
    public Long save(String name, Float price){
        return goodService.save(name, price);
    }

    @ResponseBody
    @RequestMapping("delete")
    public Long delete(Long id, HttpServletResponse response) throws IOException {
        Long delete = goodService.delete(id);
        response.sendRedirect("/?target=good-list");
        return delete;
    }

    @ResponseBody
    @RequestMapping("goodsCount")
    public Long getGoodsCount(){
        return goodService.getCount();
    }
}